<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <form id="form" action="/adduser" method="post">
        <input type="text" name="name">
        <input type="text" name='age'>
        <input type="text" name='gender'>
        <button id="btn">提交</button>
    </form>

    <script>
        const oForm = document.getElementById('form')
        const oNmae = document.querySelector('form input[name=name]')
        const oAge = document.querySelector('form input[name=age]')
        const oGender = document.querySelector('form input[name=gender]')
        const oBtn = document.getElementById('btn')


        oForm.onsubmit = function () {
            //收集表单数据
            const nameValue = oName.Value
            const ageValue = oAge.Value
            const genderValue = oGender.Value
            //实例化
            const xhr = new XMLHttpRequest();
            //初始化
            xhr.open('post', '/adduser', true)
            xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
            //发送请求
            xhr.send(JSON.stringify({
                name: nameValue,
                age: ageValue,
                sex: genderValue
            }))

            //绑定请求事件
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status <= 299)) {
                    console.log(xhr.responseText);
                }
            }
            return false;
        }

    </script>
</body>

</html>